const express = require('express')
const conn = require('../util/sql.js')
const dayjs = require('dayjs')

// 使用express下的Router方法，设置路由
const router = express.Router()
router.use(express.urlencoded())

// 上传文件索要用到的包
const multer = require('multer')

// 引入path包，取文件后缀名
const path = require('path')

const storage = multer.diskStorage({
    // 保存在哪里
    destination: function(req, file, cb) {
        cb(null, 'uploads');
    },
    // 保存时，文件名叫什么
    filename: function(req, file, cb) {
        // console.log('file', file)
        // 目标： 新名字是时间戳+后缀名
        const fileExtname = path.extname(file.originalname);
        // filenameArr.length-1是找到最后一个元素的下标
        // const fileName = Date.now() + "." + filenameArr[filenameArr.length - 1]
        // 时间戳+原图片文件的后缀名
        const fileName = Date.now() + fileExtname;
        cb(null, fileName) //
    }
})

// 精细化去设置，如何去保存文件
const upload = multer({ storage })

// 实现获取文章分类列表接口代码/my/article/cates
router.get('/cates', (req, res) => {

    const sqlStr = `select * from categories`
    conn.query(sqlStr, (err, result) => {
        console.log(err);
        console.log(result);
        if (err) return res.status(500).json({ status: 500, message: "服务器出错" })
        res.status(200).json({ status: 0, message: "获取文章分类列表成功！", data: result })
    })
})

// 实现新增文章分类接口代码/my/article/addcates
router.post('/addcates', (req, res) => {
    const { name, slug } = req.body
        // sql语句
    const sqlStr = `insert into categories(name,slug) values("${name}","${slug}")`
    conn.query(sqlStr, (err, result) => {
        console.log(err, result);
        if (err) return res.status(500).json({ status: 500, message: "服务器出错" })
        if (result.affectedRows > 0) {
            res.status(200).json({ status: 0, message: "新增文章分类成功" })
        } else {
            res.status(201).json({ status: 1, message: "新增文章分类失败" })
        }
    })
})

// 实现根据id删除分类接口代码/my/article/deletecate
router.get('/deletecate', (req, res) => {
    console.log(req.query);
    const { id } = req.query
    const sqlStr = `delete from categories where id=${id}`
    conn.query(sqlStr, (err, result) => {
        if (err) return res.status(500).json({ status: 500, message: "服务器出错" })
        if (result.affectedRows > 0) {
            res.status(200).json({ status: 0, message: "删除文章分类成功" })
        } else {
            res.status(201).json({ status: 1, message: "删除文章分类失败" })
        }
    })
})

// 实现根据id获取分类数据接口代码/my/article/getCatesById
router.get('/getCatesById', (req, res) => {
    const { id } = req.query

    // sql语句
    const sqlStr = `select * from categories where id=${id}`
    conn.query(sqlStr, (err, result) => {
        // console.log(err);
        // console.log(result);
        if (err) return res.status(500).json({ status: 500, message: "服务器出错" })
        res.status(200).json({ status: 0, message: "获取文章分类列表成功！", data: result[0] })
    })
})

// 实现更新分类数据接口代码/my/article/updatecate
router.post('/updatecate', (req, res) => {
    const { id, name, slug } = req.body
    console.log(id);
    console.log(req.body);

    // sql语句
    const sqlStr = `update categories set name="${name}",slug="${slug}" where id=${id}`
    conn.query(sqlStr, (err, result) => {
        // console.log(err);
        // console.log(result);
        if (err) return res.status(500).json({ status: 500, message: "服务器出错" })
        res.status(200).json({ status: 0, message: "更新分类信息成功!", data: result[0] })
    })
})

// 文章列表 /my/article/list
router.get("/list", (req, res) => {

    let {
        pagenum,
        pagesize,
        cate_id,
        state,
    } = req.query;

    let {
        name
    } = req.user;
    // console.log(name);

    let sql = `select id from users where username="${name}"`;

    conn.query(sql, (err, result) => {
        if (err) {
            res.status(500).json({
                code: 500,
                msg: "数据库操作失败"
            });
            return;
        }
        // console.log(result[0].id);
        let userId = result[0].id;

        // console.log(cate_name);
        let sql = `select * from list where author_id=${userId} and is_delete=0`;

        if (cate_id) sql += ` and cate_id="${cate_id}"`;
        if (state) sql += ` and state="${state}"`;

        if (pagenum && pagesize) {
            pagenum = parseInt(pagenum);
            if (pagenum == 0) {
                pagenum = pagenum;
            } else {
                pagenum = pagenum - 1;
            }

            sql += ` limit ${pagenum * pagesize},${pagesize}`;
            // console.log(sql);
        } else {
            res.status(202).json({
                code: 202,
                msg: "pagenum,pagesize 是必传参数"
            });
            return;
        }

        conn.query(sql, (err, result) => {
            if (err) {
                res.status(500).json({
                    code: 500,
                    msg: "数据库操作失败"
                });
                return;
            }

            // console.log(result);

            let listArr = result;

            let sql = `select count(*) as total from list where author_id=${userId}`;

            if (cate_id) sql += ` and cate_id="${cate_id}"`;
            if (state) sql += ` and state="${state}"`;

            conn.query(sql, (err, result) => {
                if (err) {
                    res.status(501).json({
                        code: 501,
                        msg: "数据库操作失败"
                    });
                    return;
                }
                // listArr.push(result[0])
                // console.log(listArr);

                res.status(200).json({
                    status: 0,
                    msg: "获取文章列表成功",
                    data: listArr,
                    total: result[0].total
                });
            })
        })

    })


})

// 更新文章
router.post("/add", upload.single('cover_img'), (req, res) => {
    let {
        title,
        cate_id,
        content,
        state
    } = req.body;
    console.log(req.body);

    let {
        file
    } = req;

    let {
        name
    } = req.user;
    console.log(name);

    // console.log(id, title, cate_id, file, content, state);

    let alsArr = [];
    let keyArr = [];

    if (title) {
        keyArr.push("title");
        alsArr.push(`"${title}"`);
    }

    if (cate_id) {
        keyArr.push("cate_id");
        alsArr.push(`"${cate_id}"`);
    }

    if (content) {
        keyArr.push("content");
        alsArr.push(`"${content}"`);
    }

    if (state) {
        keyArr.push("state");
        alsArr.push(`"${state}"`);
    }

    let imgSrc = "";
    if (file) {
        imgSrc = "http://127.0.0.1:3000/" + file.path.replace(/\\/g, "/");
        // console.log(imgSrc);
        keyArr.push("cover_img");
        alsArr.push(`"${imgSrc}"`);
    }

    let sql = `select name from categories where id=${cate_id}`;

    conn.query(sql, (err, result) => {
        if (err) {
            res.status(500).json({
                code: 500,
                msg: "数据库操作失败"
            });
            return;
        }
        let cate_name = result[0].name;

        if (cate_name) {
            keyArr.push("cate_name");
            alsArr.push(`"${cate_name}"`);
        }

        alsArr = alsArr.join(",");
        keyArr = keyArr.join(",");
        // console.log(result[0].name);

        let sql = `select id from users where username="${name}"`;

        conn.query(sql, (err, result) => {
            if (err) {
                res.status(500).json({
                    code: 500,
                    msg: "数据库操作失败"
                });
                return;
            }

            let author_id = result[0].id;
            console.log(author_id);

            let time = dayjs()
                .startOf('second')
                .add(1, 'day')
                .set('year', 2018)
                .format('YYYY-MM-DD HH:mm:ss');

            let sql = `insert into list(${keyArr},author_id,pub_date) values(${alsArr},${author_id},"${time}")`;

            console.log(sql);

            conn.query(sql, (err, result) => {
                if (err) {
                    res.status(500).json({
                        code: 500,
                        msg: "数据库操作失败"
                    });
                    return;
                }

                console.log(result);
                if (result.affectedRows > 0) {
                    res.status(200).json({
                        status: 0,
                        msg: "添加文章成功"
                    });
                } else {
                    res.status(201).json({
                        status: 1,
                        msg: "添加文章失败"
                    });
                }
            })
        })
    })
})

module.exports = router